package com.taxi.driver.util;

import android.text.InputFilter;
import android.text.Spanned;
import android.text.TextUtils;

/**
 * Created by Administrator on 2017/8/30.
 */
public class PointFilter implements InputFilter {

    //小数位数
    private int decimalDigits = 0;
    //最大位数
    private int maxValue = 10000;

    public PointFilter() {
    }

    public PointFilter(int decimalDigits, int maxValue) {
        this.decimalDigits = decimalDigits;
        this.maxValue = maxValue;
    }

    @Override
    public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
        if ("".equals(source.toString())) {
            return null;
        }

        if (!source.toString().matches("^[0-9]") && !".".equals(source)) {
            return null;
        }

        String dValue = dest.toString();
        String[] split = dValue.split("\\.");
        // 控制限价等价格的整数位的位数,逻辑是如果输入的数字大于设定的数据就提示
        if (TextUtils.isEmpty(dValue) && ".".equals(source)) {
            if (decimalDigits > 0) {
                return "0.";
            } else {
                return "";
            }
        }
        if (dValue.contains(".") && ".".equals(source)) {
            return "";
        }
        double dold = Double.parseDouble(dValue + source.toString());
        if (dold > maxValue) {
            return dest.subSequence(dstart, dend);
        }

        if (split.length > 1) {
            String dotValue = split[1];
            int diff = dotValue.length() + 1 - decimalDigits;
            if (diff > 0)
                return source.subSequence(start, end - diff);
        }
        return null;
    }
}
